#include "stdafx.h"
#include "Utilities/utilities.h" // if you use STL, please include this line AFTER all other include
#include "Texture.h"
#include "Shader.h"


void Texture::SetTextureFileName (const char * str)
{
	strcpy_s(m_szTextureFileName, 255, str);
}

void Texture::SetTextureTiling(GLint tiling)
{
	m_tiling = tiling;
}

void Texture::Init ()
{
	int iWidth, iHeight, iBpp;
	GLuint format = GL_RGB;

	//Load TGA
	char * imageData = LoadTGA(m_szTextureFileName, &iWidth, &iHeight, &iBpp);
	if (iBpp == 24)
		format = GL_RGB;
	else if (iBpp == 32)
		format = GL_RGBA;

	//Create texture buffer inside VRAM
	glGenTextures(1, &m_textureId);
	glBindTexture(GL_TEXTURE_2D, m_textureId);

	glTexImage2D(GL_TEXTURE_2D, 0, format, iWidth, iHeight, 0, format, GL_UNSIGNED_BYTE, imageData);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, m_tiling);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, m_tiling);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, m_magFilter);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, m_minFilter);
	
	//assume if this minFilter != LINEAR and NEAREST means it will be mipmap texture method
	if (m_minFilter != GL_LINEAR && m_minFilter != GL_NEAREST)
		glGenerateMipmap(GL_TEXTURE_2D);

	glBindTexture(GL_TEXTURE_2D, 0);
}

void Texture::Bind (Shader * shader, GLint idx, bool bMulti)
{
	glActiveTexture(GL_TEXTURE0 + idx);
	glBindTexture(GL_TEXTURE_2D, m_textureId);
	
	if (!bMulti)
	{
		if(shader->m_textureUniform != -1)
			glUniform1i(shader->m_textureUniform, 0);
	}
	else
	{
		if(shader->m_multiTexturesUniform[idx] != -1) 
			glUniform1i(shader->m_multiTexturesUniform[idx], idx);
	}
}

void Texture::UnBind ()
{
	glBindTexture(GL_TEXTURE_2D, 0);
}

void Texture::CleanUp ()
{
	glDeleteTextures(1, &m_textureId);
}